<?php
  include 'weixinConfig.php';
  $m = memcache_init();

  $openid = $_GET['openid'];
  $action = $_GET['action'];

  $accessToken_arr = $m->get('accessToken_arr');

  if($accessToken_arr['expire'] < time()){

    $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.APPID.'&secret='.SECRET;
    $accessTokenJson = request($url, 'GET', null);
    $accessToken = json_decode($accessTokenJson)->access_token;
    $accessToken_arr = array('accessToken'=>$accessToken, 'expire'=>time()+7000);

    $m->set('accessToken_arr', $accessToken_arr);

  }
  $accessToken = $accessToken_arr['accessToken'];

  switch ($action) {
    case 'getUserInfo':
      $raw = getUserInfo($accessToken, $openid);
      echo urldecode(json_encode($raw));
      break;
    case 'sendText':
      sendText($accessToken, $openid, $_GET['content']);
      break;
    default:
      # code...
      break;
  }


  function getUserInfo($accessToken, $openid){
    $url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$accessToken.'&openid='.$openid;
    return request($url, 'GET');
  }
  function sendText($accessToken, $openid, $content){
    $url = '';
    $data json_encode(array("touser"=>$openid, "msgtype"=> "text", "text"=> array("content"=>$content)));
    return request($url, 'post', $data)
  }


  function request($url, $method, $data=null){
    $ch = curl_init();
    if(strtolower($method) == 'get'){
      curl_setopt($ch,CURLOPT_URL,$url);
  		curl_setopt($ch,CURLOPT_SSLVERSION,CURL_SSLVERSION_TSLv1);
  		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    }
    else if(strtolower($method) == 'post'){
      curl_setopt($ch,CURLOPT_URL,$url);
  		curl_setopt($ch,CURLOPT_POST,true);
  		curl_setopt($ch,CURLOPT_SSLVERSION,CURL_SSLVERSION_TSLv1);
  		curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
  		curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
    }
    return curl_exec($ch);
    curl_close($ch);
  }

?>
